import 'package:flutter/material.dart';

//流式布局
class FlowWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text("Flow"),
          leading: new BackButton(),
        ),
        body: Flow(
          delegate: ZFlowDelegate(margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0)),
          children: <Widget>[
            Container(
              width: 80,
              height: 60,
              color: Colors.yellow,
            ),
            Container(
              width: 120,
              height: 60,
              color: Colors.green,
            ),
            Container(
              width: 40,
              height: 60,
              color: Colors.grey,
            ),
            Container(
              width: 50,
              height: 60,
              color: Colors.red,
            ),
            Container(
              width: 70,
              height: 60,
              color: Colors.black,
            ),
            Container(
              width: 70,
              height: 60,
              color: Colors.blue,
            ),
            Container(
              width: 20,
              height: 60,
              color: Colors.orange,
            ),
            Container(
              width: 110,
              height: 60,
              color: Colors.cyan,
            ),
            Container(
              width: 20,
              height: 60,
              color: Colors.pink,
            ),
          ],
        ));
  }
}

class ZFlowDelegate extends FlowDelegate {
  EdgeInsets margin;

  ZFlowDelegate({this.margin = EdgeInsets.zero});

  @override
  void paintChildren(FlowPaintingContext context) {
    var x = margin.left;
    var y = margin.top;
    for (int i = 0; i < context.childCount; i++) {
      var w = context.getChildSize(i)!.width + x + margin.right;
      if (w < context.size.width) {
        context.paintChild(i,
            transform: new Matrix4.translationValues(x, y, 0.0));
        x = w + margin.left;
      } else {
        x = margin.left;
        y += context.getChildSize(i)!.height + margin.top + margin.bottom;
        context.paintChild(i,
            transform: new Matrix4.translationValues(x, y, 0.0));
        x += context.getChildSize(i)!.width + margin.left + margin.right;
      }
    }
  }

  @override
  bool shouldRepaint(FlowDelegate oldDelegate) {
    return oldDelegate != this;
  }
}
